package com.bloveoacom.weichi.fragment;

import android.app.Dialog;
import android.os.Bundle;
import android.support.constraint.Group;
import android.support.v4.content.ContextCompat;
import android.text.InputType;
import android.text.Layout;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.blankj.utilcode.util.SpanUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bloveoacom.base.BaseListFragment;
import com.bloveoacom.base.UserInfoBean;
import com.bloveoacom.exception.ApiException;
import com.bloveoacom.http.HttpMethods;
import com.bloveoacom.http.HttpResult;
import com.bloveoacom.observer.BaseSubscriber2;
import com.bloveoacom.util.AESCipher;
import com.bloveoacom.util.ActivityUtil;
import com.bloveoacom.util.DialogUtil;
import com.bloveoacom.util.GlideUtil;
import com.bloveoacom.util.GsonUtil;
import com.bloveoacom.util.NumberUtil;
import com.bloveoacom.util.StringUtils;
import com.bloveoacom.util.ToastUtil;
import com.bloveoacom.weichi.R;
import com.bloveoacom.weichi.activity.BuyRecordActivity;
import com.bloveoacom.weichi.activity.CheckActivity;
import com.bloveoacom.weichi.activity.ContactUsActivity;
import com.bloveoacom.weichi.activity.ContentActivity;
import com.bloveoacom.weichi.activity.CreateWalletActivity;
import com.bloveoacom.weichi.activity.MyAttentionActivity;
import com.bloveoacom.weichi.activity.MyCollectActivity;
import com.bloveoacom.weichi.activity.SettingActivity;
import com.bloveoacom.weichi.activity.ShareActivity;
import com.bloveoacom.weichi.activity.TransActivity;
import com.bloveoacom.weichi.activity.UserinfoActivity;
import com.bloveoacom.weichi.adapter.MyBaseAdapter;
import com.bloveoacom.weichi.bean.CreateEosWalletBean;
import com.bloveoacom.weichi.bean.ItemOptionBean;
import com.bloveoacom.weichi.bean.RewardBean;
import com.bloveoacom.weichi.bean.SimpleBean;
import com.bloveoacom.weichi.bean.UserBean;
import com.bloveoacom.weichi.contract.MineContract;
import com.bloveoacom.weichi.model.MineModel;
import com.bloveoacom.weichi.presenter.MinePresenter;
import com.bloveoacom.weight.InputDialog;
import com.chad.library.adapter.base.BaseQuickAdapter;

import org.reactivestreams.Publisher;

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

import static com.bloveoacom.util.AESCipher.KEY;
import static com.bloveoacom.util.DataUtil.QD;
import static com.bloveoacom.util.DataUtil.getReward;
import static com.bloveoacom.util.DataUtil.showMsg;

/**
 * author: zhu.px
 * e-mail: 1271901673@qq.com
 * time  : 2018/5/8
 * desc  : 我的
 */
public class MineFragment extends BaseListFragment<MinePresenter, MineModel, BaseQuickAdapter> implements MineContract.View {


    public static MineFragment newInstance() {
        Bundle args = new Bundle();
        MineFragment fragment = new MineFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getLayoutResId() {
        return R.layout.layout_refresh;
    }


    @Override
    public boolean isSetBarColor() {
        return false;
    }

    @Override
    public void initView() {
        super.initView();
        setShowPrivetKeyDialog();
    }

    @Override
    protected void initSetting() {
        mAdapter = new MyBaseAdapter(R.layout.item_option_data2, new ArrayList());
        mAdapter.addHeaderView(getHeaderView());
    }


    ViewHolder viewHolder;

    private View getHeaderView() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.header_mine, null);
        viewHolder = new ViewHolder(view);
        return view;
    }

    @Override
    protected boolean isOpenRefresh() {
        return true;
    }

    @Override
    public void initData() {
        //setUserinfo();
        setNoLoginHeader();
    }

    public void setUserinfo() {
        if (UserInfoBean.getInstance().isLogin()) {
            if(mPresenter!=null)
              mPresenter.getUserInfo();
        } else {
            setNoLoginHeader();
        }
    }
    public void setNoLoginHeader(){
        if(viewHolder==null)
            return;
        GlideUtil.loadCircleImage(viewHolder.ivHeader, R.drawable.ic_header_default);
        viewHolder.tv_username.setText("请登录");
        viewHolder.tvPost.setText(getSu(postNum, "帖子").create());
        viewHolder.tvFans.setText(getSu(fansNum, "粉丝").create());
        viewHolder.tvAttention.setText(getSu(attentionsNum, "关注").create());
        viewHolder.tvAccountName.setText(getString(R.string.eos_account, getString(R.string.zwf)));
        viewHolder.tvBalance.setText(getString(R.string.tu_balance, getString(R.string.zwf)));
    }


    @Override
    public void getBundleExtras(Bundle extras) {

    }

    @Override
    public void initListener() {
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                switch (position) {
                    case 0:
                        if (isLogin()) {
                            ActivityUtil.startActivity(mContext, CheckActivity.class);
                        }
                        break;
                    case 1:
                        if (isLogin()) {
                            ActivityUtil.startActivity(mContext, BuyRecordActivity.class);
                        }
                        break;
                    case 2:
                        if (isLogin()) {
                            ActivityUtil.startActivity(mContext, MyCollectActivity.class);
                        }
                        break;
                    case 3:
                        if (isLogin()) {
                            ActivityUtil.startActivity(mContext, ShareActivity.class);
                        }
                        break;
                    case 4:
                        if (isLogin()) {
                            ActivityUtil.startActivity(mContext, ContactUsActivity.class);
                        }
                    case 5:
                        if (isLogin()) {
                            ActivityUtil.startActivity(mContext, SettingActivity.class);
                        }
                        break;
                }
            }
        });
    }

    @Override
    public void getOps(List<ItemOptionBean> datas) {
        loadDataComplete(datas);
    }

    @Override
    public void setUserInfo(UserBean userInfo) {
        UserBean userBean = userInfo;
        balanceNum = userBean.emtNum;
        postNum = userBean.coinBarNum;
        fansNum = userBean.fansNum;
        attentionsNum = userBean.focusNum;
        UserInfoBean.getInstance().setAccess(userBean);
        setHeaderData();
    }

    @Override
    public void userSignIn(Object o) {
        String s = GsonUtil.GsonString(o);
        RewardBean rewardBean = GsonUtil.GsonToBean(s, RewardBean.class);
        showMsg(mContext,rewardBean,R.drawable.ic_like_reward,"已签到",QD);
    }

     class ViewHolder {
        @BindView(R.id.iv_header)
        ImageView ivHeader;
        @BindView(R.id.tv_fans)
        TextView tvFans;
        @BindView(R.id.tv_username)
        TextView tv_username;
        @BindView(R.id.tv_attention)
        TextView tvAttention;
        @BindView(R.id.tv_post)
        TextView tvPost;
        @BindView(R.id.tv_balance)
        TextView tvBalance;
        @BindView(R.id.tv_account_name)
        TextView tvAccountName;
        @BindView(R.id.tv_account_copy)
        TextView tvAccountCopy;
        @BindView(R.id.group_one)
        Group group_one;
        @BindView(R.id.group_two)
        Group group_two;
        @BindView(R.id.iv_balance_open)
        ImageView ivBalanceOpen;

        @OnClick({R.id.tv_account_create, R.id.tv_post, R.id.tv_fans, R.id.tv_username, R.id.tv_attention, R.id.tv_account_copy, R.id.iv_header, R.id.tv_account_name, R.id.no_view4_use, R.id.iv_balance_open})
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.tv_account_copy:
                    if (isLogin()) {
                        StringUtils.copyText(UserInfoBean.getInstance().getWalletAccount());
                        ToastUtil.makeShortText(mContext, "复制成功");
                    }
                    break;
                case R.id.iv_header:
                case R.id.tv_username:
                    if (isLogin()) {
                        ActivityUtil.startActivity(mContext, UserinfoActivity.class);
                    }
                    break;
                case R.id.tv_account_create:
                    if (isLogin()) {
                        if (StringUtils.isEmpty(UserInfoBean.getInstance().getWalletAccount())) {
                            ActivityUtil.startActivity(mContext, CreateWalletActivity.class);
                        }
                    }
                    break;
                case R.id.no_view4_use:
                    if (isLogin()) {
                        if (!StringUtils.isEmpty(UserInfoBean.getInstance().getWalletAccount())) {
                            ActivityUtil.startActivity(mContext, TransActivity.class);
                        }
                    }
                    break;
                case R.id.iv_balance_open:
                    if (isLogin()) {
//                        ivBalanceOpen.setSelected(!ivBalanceOpen.isSelected());
//                        viewHolder.tvBalance.setText(getString(R.string.tu_balance,!viewHolder.ivBalanceOpen.isSelected()?balanceNum:"******"));
                        showInputPasswordDialog();
                    }
                    break;
                case R.id.tv_fans:
                    if (isLogin()) {
                        MyAttentionActivity.startA(mContext, 0, UserInfoBean.getInstance().getUid(), "我的粉丝");
                    }
                    break;
                case R.id.tv_post:
                    if (isLogin()) {
                        ActivityUtil.startActivity(mContext, ContentActivity.class);
                    }
                    break;
                case R.id.tv_attention:
                    if (isLogin()) {
                        MyAttentionActivity.startA(mContext, 1, UserInfoBean.getInstance().getUid(), "我的关注");
                    }
                    break;
            }
        }

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

    private String postNum = "0", fansNum = "0", attentionsNum = "0", balanceNum = "0";

    public void setHeaderData() {
        if(viewHolder==null)
            return;
        GlideUtil.loadCircleImage(viewHolder.ivHeader, StringUtils.getFullUrl(UserInfoBean.getInstance().getHeader(), 0));
        viewHolder.tv_username.setText(new SpanUtils().append(UserInfoBean.getInstance().getNickName()).create());
        if (StringUtils.isEmpty(UserInfoBean.getInstance().getWalletAccount())) {
            viewHolder.group_one.setVisibility(View.GONE);
            viewHolder.group_two.setVisibility(View.VISIBLE);
        } else {
            viewHolder.group_one.setVisibility(View.VISIBLE);
            viewHolder.group_two.setVisibility(View.GONE);
        }
        viewHolder.tvAccountName.setText(getString(R.string.eos_account, StringUtils.isEmpty(UserInfoBean.getInstance().getWalletAccount()) ? "创建账号" : UserInfoBean.getInstance().getWalletAccount()));
        viewHolder.tvPost.setText(getSu(postNum, "帖子").create());
        viewHolder.tvFans.setText(getSu(fansNum, "粉丝").create());
        viewHolder.tvAttention.setText(getSu(attentionsNum, "关注").create());
        viewHolder.tvBalance.setText(getString(R.string.tu_balance, !viewHolder.ivBalanceOpen.isSelected() ? balanceNum : "******"));
    }

    private SpanUtils getSu(String fdata, String sData) {
        return new SpanUtils().appendLine(fdata).setAlign(Layout.Alignment.ALIGN_CENTER).setForegroundColor(ContextCompat.getColor(mContext, R.color.black)).setFontSize(14, true).append(sData).setAlign(Layout.Alignment.ALIGN_CENTER).setFontSize(12, true);
    }

    private InputDialog inputPasswordDialog;
    private Dialog dialog2;


    private void setShowPrivetKeyDialog(){
        dialog2 = DialogUtil.getDialg(mContext,getDialogView(),false,false);
    }
    private void showInputPasswordDialog() {
        if (inputPasswordDialog == null) {
            inputPasswordDialog = new InputDialog(mContext, "输入密码", "Password", true, false, R.style.MyDialogStyle);
            inputPasswordDialog.setItemClickListener(new InputDialog.ItemClickListener() {
                @Override
                public void left() {

                }

                @Override
                public void right(String content) {
                    DialogUtil.dissDialog(inputPasswordDialog);
                    BaseSubscriber2<HttpResult<Object>> baseSubscriber2 = HttpMethods.getInstance().getHttpService().findTimeStamp(UserInfoBean.getInstance().getToken()).subscribeOn(Schedulers.io()).flatMap(new Function<HttpResult<Object>, Publisher<HttpResult<Object>>>() {
                        @Override
                        public Publisher<HttpResult<Object>> apply(HttpResult<Object> objectHttpResult) throws Exception {
                            if (objectHttpResult.isOk()) {
                                Object o = objectHttpResult.data;
                                SimpleBean simpleBean = GsonUtil.GsonToBean(GsonUtil.GsonString(o), SimpleBean.class);
                                String s = AESCipher.decryptAES(simpleBean.timeStamp);
                                CreateEosWalletBean transInfoBean = new CreateEosWalletBean(content, s);
                                String s1 = AESCipher.encryptAES(GsonUtil.GsonString(transInfoBean), KEY);
                                return HttpMethods.getInstance().getHttpService().getUserKey(UserInfoBean.getInstance().getToken(), s1);
                            } else {
                                return Flowable.error(new ApiException(objectHttpResult.code, objectHttpResult.msg));
                            }
                        }
                    }).observeOn(AndroidSchedulers.mainThread()).subscribeWith(new BaseSubscriber2<HttpResult<Object>>(MineFragment.this) {
                        @Override
                        public void onNext(HttpResult<Object> o) {
                            super.onNext(o);
                            if (o.isOk()) {
                                String json = GsonUtil.GsonString(o.data);
                                UserBean userRegisterBean = GsonUtil.GsonToBean(json, UserBean.class);
                                UserInfoBean.getInstance().setWalletAccount(userRegisterBean.walletAccount);
                                try {
                                    privateKey = AESCipher.decryptAES(userRegisterBean.privateKey);
                                    UserInfoBean.getInstance().setPrivateKey(privateKey);
                                    holder2.tvPriKey.setText(privateKey);
                                    DialogUtil.showDialog(dialog2);
                                } catch (InvalidKeyException e) {
                                    e.printStackTrace();
                                } catch (NoSuchAlgorithmException e) {
                                    e.printStackTrace();
                                } catch (NoSuchPaddingException e) {
                                    e.printStackTrace();
                                } catch (InvalidAlgorithmParameterException e) {
                                    e.printStackTrace();
                                } catch (IllegalBlockSizeException e) {
                                    e.printStackTrace();
                                } catch (BadPaddingException e) {
                                    e.printStackTrace();
                                } catch (UnsupportedEncodingException e) {
                                    e.printStackTrace();
                                }
                            } else {
                                ToastUtil.makeShortText(mContext, o.msg);
                            }
                        }
                    });
                    addDispose(baseSubscriber2);
                }
            });
        }
        inputPasswordDialog.show();
    }


    private String privateKey;

    ViewHolder2 holder2;
    public View getDialogView() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_show_privatekey, null);
         holder2 = new ViewHolder2(view);
        return view;
    }


    class ViewHolder2 {
        @BindView(R.id.tv_pri_key)
        TextView tvPriKey;

        @OnClick({R.id.iv_close,R.id.btn_copy})
        public void click(View view){
            switch (view.getId()) {
                case R.id.iv_close:
                    DialogUtil.dissDialog(dialog2);
                    inputPasswordDialog.clearContent();
                    break;
                case R.id.btn_copy:
                    StringUtils.copyText(privateKey);
                    ToastUtil.makeShortText(mContext,"复制成功");
                    DialogUtil.dissDialog(dialog2);
                    inputPasswordDialog.clearContent();
                    break;
            }
        }
        ViewHolder2(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
